
package guoan.service;

import guoan.core.common.WebConfig;
import guoan.core.dto.DataGridModel;
import guoan.core.dto.PageResponse;
import guoan.domain.AutoForm;
import guoan.domain.AutoFormInput;
import guoan.domain.AutoFormValue;
import guoan.repository.AutoFormInputRepository;
import guoan.repository.AutoFormRepository;
import guoan.repository.AutoFormValueRepository;
import guoan.service.weixin.WeiXinService;

import java.util.List;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

@Service
@Transactional(readOnly = false)
public class AutoFormService extends PageSerivce<AutoForm> {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private AutoFormRepository autoFormRepository;

    @Autowired
    private AutoFormInputRepository autoFormInputRepository;

    @Autowired
    private AutoFormValueRepository autoFormValueRepository;
    @Autowired
    private MediaService mediaService;
    @Autowired
    private KeywordService keywordService;
    @Autowired
    private WeiXinService weiXinService;

    public List<String> findFormInputNames(Long autoFormId){
        // TODO Auto-generated method stub
        return autoFormInputRepository.findFormInputNames(autoFormId);
    }

    public AutoForm findOne(Long autoFormId){
        // TODO Auto-generated method stub
        return autoFormRepository.findOne(autoFormId);
    }

    public PageResponse<Object[]> page(Long autoFormId, DataGridModel dgm){
        // TODO Auto-generated method stub
        // 排序后的表单字段
        List<Object[]> ro = Lists.newArrayList();
        String sql = "SELECT form_id FROM 	auto_form_value WHERE 	auto_form_id = "
                + autoFormId + " GROUP BY form_id ORDER BY create_time DESC";
        PageResponse<Object[]> pp = this.queryPageByJpql(sql, dgm);
        List<AutoFormInput> auis = this.findByAutoFormIdOrderByOrderIdDesc(autoFormId);
        List<Object[]> forids = pp.getAaData();
        for (int i = 0; i < forids.size(); i++) {
        	List<Object> vO = Lists.newArrayList();
        	String formId = String.valueOf(forids.get(i));
        	for(AutoFormInput autoFormInput:auis){
        		AutoFormValue vaule = this.findValueByAutoFormInputIdAndFormId(autoFormInput.getId(),formId);
        		vO.add(vaule == null ? null: vaule.getValue());
        	}
        	vO.add(formId);
            ro.add(vO.toArray());
        }
        pp.setAaData(ro);

        return pp;
    }

    private AutoFormValue findValueByAutoFormInputIdAndFormId(Long id,String formId) {
		// TODO Auto-generated method stub
		return autoFormValueRepository.findOneByAutoFormInputIdAndFormId(id,formId);
	}

	public List<Object[]> findFormInfo(String formid){
        // TODO Auto-generated method stub
        return autoFormValueRepository.findFormValue(formid);
    }

    public List<AutoFormInput> findByAutoFormIdOrderByOrderIdDesc(
            Long autoFormId){
        // TODO Auto-generated method stub
        return autoFormInputRepository
                .findByAutoFormIdOrderByOrderIdDesc(autoFormId);
    }

    public void addAutoFormValue(List<AutoFormValue> autoFormValueList){
        // TODO Auto-generated method stub
        autoFormValueRepository.save(autoFormValueList);
    }

    public PageResponse<AutoForm> page(DataGridModel dataGridModel){
        // TODO Auto-generated method stub
        return pageResponse(autoFormRepository, dataGridModel);
    }

    public void save(AutoForm autoForm){
        // TODO Auto-generated method stub

        if (autoForm.getId() == null) {
            autoForm.setCreateTime(new DateTime());
            /*if (autoForm.getImgUrl() != null) {
                WxUpload wxUpload = weiXinService
                        .uploadMedia(WebConfig.WEIXIN_MEDIA_IMG, path
                                + autoForm.getImgUrl());
                if (wxUpload != null) {
                    Media media = new Media();
                    media.setFileUrl(autoForm.getImgUrl());
                    media.setMediaId(wxUpload.getMedia_id());
                    media.setCreateTime(new DateTime(Long.valueOf(wxUpload
                            .getCreated_at() + "000")));
                    media.setType(WebConfig.WEIXIN_MEDIA_IMG);
                    mediaService.add(media);
                    autoForm.setMedia(media);
                }
            }*/
            autoFormRepository.save(autoForm);
            keywordService.add(autoForm.getKeyName(),
                    WebConfig.KEYWORD_KEY_INFO_AUTOFROM, autoForm.getId());
        } else {
            AutoForm oldAutoForm = autoFormRepository.findOne(autoForm.getId());
            oldAutoForm.setInfo(autoForm.getInfo());
            oldAutoForm.setName(autoForm.getName());
            oldAutoForm.setContent(autoForm.getContent());
            oldAutoForm.setLastTime(autoForm.getLastTime());

           /* if (autoForm.getImgUrl() != null) {
                if (!autoForm.getImgUrl().equals(oldAutoForm.getImgUrl())) {
                    WxUpload wxUpload = weiXinService.uploadMedia(
                            WebConfig.WEIXIN_MEDIA_IMG,
                            path + autoForm.getImgUrl());
                    if (wxUpload != null) {
                        Media media = new Media();
                        media.setFileUrl(autoForm.getImgUrl());
                        media.setMediaId(wxUpload.getMedia_id());
                        media.setCreateTime(new DateTime(Long.valueOf(wxUpload
                                .getCreated_at() + "000")));
                        media.setType(WebConfig.WEIXIN_MEDIA_IMG);
                        mediaService.add(media);
                        oldAutoForm.setMedia(media);
                    }
                    oldAutoForm.setImgUrl(autoForm.getImgUrl());
                }
            }*/
            String oldk = oldAutoForm.getKeyName();
            oldAutoForm.setKeyName(autoForm.getKeyName());
            autoFormRepository.save(oldAutoForm);
            // 如果更改了关键字则删除老的新建新的
            if (!autoForm.getKeyName().equals(oldk)) {
                keywordService.delete(WebConfig.KEYWORD_KEY_INFO_AUTOFROM,
                        oldAutoForm.getId());
                keywordService.add(autoForm.getKeyName(),
                        WebConfig.KEYWORD_KEY_INFO_AUTOFROM,
                        oldAutoForm.getId());
            }
        }
    }

    public void del(Long id){
        // TODO Auto-generated method stub
        autoFormRepository.delete(id);  
        keywordService.delete(WebConfig.KEYWORD_KEY_INFO_AUTOFROM, id);

    }
}
